package com.websocket.websocketproject.websocket;

import com.websocket.websocketproject.config.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ChatMessageHandler extends TextWebSocketHandler {

    private static final Map<String, WebSocketSession> map;// 这个会出现性能问题，最好用Map来存储，key用userid


    static {
        map = new HashMap<>();
    }

    /**
     * 连接成功时候，会触发UI上onopen方法
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("connect to the websocket success......");
        map.put(Constants.WEBSOCKET_USERNAME, session);
    }

    /**
     * 在UI在用js调用websocket.send()时候，会调用该方法
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        sendMessageToUser(Constants.WEBSOCKET_USERNAME,message);
        //super.handleTextMessage(session, message);
    }

    /**
     * 给某个用户发送消息
     *
     * @param userName
     * @param message
     */
    public void sendMessageToUser(String userName, TextMessage message) {
        WebSocketSession webSocketSession = map.get(Constants.WEBSOCKET_USERNAME);
        try {
                webSocketSession.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        log.debug("websocket connection closed......");
        map.remove(Constants.WEBSOCKET_USERNAME);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        log.debug("websocket connection closed......");
        map.remove(Constants.WEBSOCKET_USERNAME);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

}